import React from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Col, Row, Button, Input, Select, Divider, Dropdown, Menu, message } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { Option } = Select;
@connect(({ pricing, loading }) => ({
  pageData: pricing.pageData,
  loading: loading.effects['pricing/fetchList'],
  formFieldsValue: pricing.formFieldsValue,
  expandForm: pricing.expandForm,
  valuesArr: pricing.valuesArr,
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      PD_CATE: [],
      selectedRows: [],
      selectedRowKeys: [],
    };
    this.formItemLayout = {
      labelCol: {
        span: 7,
      },
      wrapperCol: {
        span: 17,
      },
    };
  }

  componentDidMount() {
    const {
      location,
      dispatch,
    } = this.props;
    const tempUrl = location.pathname && location.pathname.split('/index')[0];
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['PD_CATE'],
    }).then(data => {
      this.setState({
        PD_CATE: data.PD_CATE,
      });
    });
    this.setState({ tempUrl });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'pricing/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'pricing/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    currentPage = 1,
    pageSize = 10,
  ) => {
    const { dispatch } = this.props;
    const pagerArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pagerArg,
    };

    dispatch({
      type: 'pricing/updateModelData',
      payload: {
        values,
      },
    });
    dispatch({
      type: 'pricing/fetchList',
      payload: {
        ...values,
      },
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'pdName' || key === 'pdCode') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] =
          tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
    });
    return formFieldsValue;
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'pricing/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 查看详情
  goDetails = (e, record) => {
    e.preventDefault();
    router.push(
      encodeURI(
        `/productmanage/pricesearch/detail?pdId=${record.pdId}&specifId=${record.specifId}&pdName=${
          record.pdName
        }`
      )
    );
  };

  // 修改信息
  update = record => {
    router.push(`/productmanage/pricesearch/update?pdId=${record.pdId}`);
  };

  // 添加规则
  addRules = record => {
    const { tempUrl } = this.state;
    if (record.openFlag && record.openFlag === 2) {
      message.warning(`当前产品已经停用，不接添加售价规则`);
    } else {
      router.push(`${tempUrl}/speicf?pdId=${record.pdId}`);
    }
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'pricing/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="产品名称" {...this.formItemLayout}>
              {getFieldDecorator('pdName', {
                initialValue: formFieldsValue.pdName,
              })(<Input placeholder="请输入" maxLength={20} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="产品编号" {...this.formItemLayout}>
              {getFieldDecorator('pdCode', {
                initialValue: formFieldsValue.pdCode,
              })(<Input placeholder="请输入" maxLength={20} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    const { PD_CATE } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="产品名称" {...this.formItemLayout}>
              {getFieldDecorator('pdName', {
                initialValue: formFieldsValue.pdName,
              })(<Input placeholder="请输入" maxLength={20} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="产品编号" {...this.formItemLayout}>
              {getFieldDecorator('pdCode', {
                initialValue: formFieldsValue.pdCode,
              })(<Input placeholder="请输入" maxLength={20} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="分类" {...this.formItemLayout}>
              {getFieldDecorator('pdCate', {
                rules: [{ required: false, message: '请选择' }],
                initialValue: formFieldsValue.pdCate,
              })(
                <Select
                  placeholder="请选择"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {PD_CATE.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { tempUrl, selectedRows, selectedRowKeys } = this.state;
    const { pageData, loading } = this.props;
    const columns = [
      {
        title: '产品编号',
        dataIndex: 'pdCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '产品名称',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '产品分类',
        dataIndex: 'pdCateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '默认建议售价',
        dataIndex: 'suggPrice',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val || val === 0 ? val : '--'),
      },
      {
        title: '建议售价规则数',
        dataIndex: 'specifNum',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => router.push(`${tempUrl}/detail?pdId=${record.pdId}&isDetail=true`)}>
              查看
            </a>
            {checkPermissions([
              'mgr:baseProductQuery:insertSpeicf',
              'mgr:baseProductQuery:inertSpeicfPrice',
            ]) && <Divider type="vertical" />}
            {checkPermissions([
              'mgr:baseProductQuery:insertSpeicf',
              'mgr:baseProductQuery:inertSpeicfPrice',
            ]) && (
              <Dropdown
                overlay={
                  <Menu>
                    {checkPermissions(['mgr:baseProductQuery:insertSpeicf']) && (
                      <Menu.Item
                        key="update"
                        onClick={() => router.push(`${tempUrl}/update?pdId=${record.pdId}`)}
                      >
                        修改
                      </Menu.Item>
                    )}
                    {checkPermissions(['mgr:baseProductQuery:inertSpeicfPrice']) && (
                      <Menu.Item
                        key="addSpe"
                        onClick={() => this.addRules(record)}
                      >
                        添加规则
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多
                  <DownOutlined />
                </a>
              </Dropdown>
            )}
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Authorized authority="mgr:baseProductQuery:insertSpeicf" noMatch={null}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              style={{ marginBottom: 16 }}
              onClick={() => router.push('/productmanage/pricing/add')}
            >
              新增
            </Button>
          </Authorized>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={pageData}
            rowKey="priceId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
